package com.zoro.barn.business.service.pp.business.product.service;

import com.zoro.barn.business.service.pp.business.product.dao.BarnProductUserMapper;
import com.zoro.barn.business.service.pp.business.product.entity.BarnProductUser;
import com.zoro.barn.commons.tools.string.IDs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnProductUserService {
    @Resource
    private BarnProductUserMapper barnProductUserMapper;

    /**
     * add users for a product
     *
     * @param productId product id
     * @param userIds   user ids
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUsers(String productId, String[] userIds) {

        if (StringUtils.isBlank(productId) || userIds == null || userIds.length == 0) {
            return;
        }

        Set<String> ids = new HashSet<>(Arrays.asList(userIds));
        Set<BarnProductUser> data = ids.stream().filter(id -> barnProductUserMapper.hasUser(productId, id) == 0).map(id -> {
            BarnProductUser bu = new BarnProductUser();
            bu.setPid(IDs.uuid());
            bu.setProductId(productId);
            bu.setUserId(id);
            return bu;
        }).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(data)) {
            return;
        }
        this.barnProductUserMapper.insertBatch(data);
    }

    public List<BarnProductUser> getUsers(String productId) {
        BarnProductUser param = new BarnProductUser();
        param.setProductId(productId);
        return this.barnProductUserMapper.query(param);
    }

    public void deleteUser(String productId, String userId) {
        this.barnProductUserMapper.deleteUser(productId,userId);
    }
}
